<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 顶部按钮 -->
      <div class="topOperation">
        <el-button
          :disabled="crud.selections.length <= 0"
          type="primary"
          round
          @click="disDialog({ label: '转移患者', value: 'transfer' })"
        >转移患者</el-button>
        <el-button :disabled="crud.selections.length <= 0" type="primary" round @click="toDelete()">
          删除患者</el-button>
        <el-button :disabled="crud.selections.length <= 0" type="primary" round @click="disDialog({ label: '规则配置', value: 'rule' })">规则配置</el-button>
      </div>
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select
          v-model="query.patientName"
          filterable
          remote
          reserve-keyword
          placeholder="搜索患者姓名"
          class="inline-input filter-item"
          style="width: 200px"
          :remote-method="queryPatientName"
          :loading="loading"
        >
          <el-option v-for="item in patientNameList" :key="item.id" :label="item.label" :value="item.label">
          </el-option>
        </el-select>
        <el-select
          v-model="query.clinicId"
          filterable
          remote
          reserve-keyword
          placeholder="诊所名称"
          class="inline-input filter-item"
          style="width: 200px"
          :remote-method="queryClinicName"
          :loading="loading"
        >
          <el-option v-for="item in clinicNameList" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
        <el-select
          v-model="query.groupId"
          filterable
          remote
          reserve-keyword
          placeholder="所属集团"
          class="inline-input filter-item"
          style="width: 200px"
          :remote-method="queryGroupName"
          :loading="loading"
        >
          <el-option v-for="item in groupNameList" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
        <el-input
          v-model="query.salesId"
          clearable
          placeholder="销售"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        ></el-input>
        <el-select
          v-model="query.proCode"
          placeholder="省份"
          clearable
          style="width: 200px"
          class="filter-item"
          @change="provinceChange"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in province" :key="item.code" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
        <el-select
          v-model="query.cityCode"
          placeholder="城市"
          clearable
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in city" :key="item.code" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
        <el-select
          v-model="query.packageId"
          placeholder="套餐类型"
          clearable
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in packageNameList" :key="item.id" :label="item.packageName" :value="item.id">
          </el-option>
        </el-select>
        <el-select
          v-model="query.productId"
          placeholder="矫治器类型"
          clearable
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in productNameList" :key="item.id" :label="item.productName" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="query.stlFlag" placeholder="牙模类型" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in dict.stl_flag" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="query.recordStat" placeholder="诊疗状态" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in dict.record_stat" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="query.phase" placeholder="诊疗阶段" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in dict.medical_phase" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-input
          v-model="query.id"
          clearable
          placeholder="搜索患者编号"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        ></el-input>
        <el-select
          v-model="query.doctorId"
          filterable
          remote
          reserve-keyword
          placeholder="主治医生"
          class="inline-input filter-item"
          style="width: 200px"
          :remote-method="queryDoctorName"
          :loading="loading"
        >
          <el-option v-for="item in doctorNameList" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
        <el-input
          v-model="query.areaId"
          clearable
          placeholder="区域"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        ></el-input>
        <el-select
          v-model="query.clinicType"
          clearable
          placeholder="诊所性质"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
          <el-option v-for="item in dict.clinic_type" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-model="query.submitDate"
          type="date"
          value-format="timestamp"
          format="yyyy-MM-dd 00:00:00"
          clearable
          placeholder="提交资料时间"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
        </el-date-picker>
        <el-date-picker
          v-model="query.dentalCastRecvDate"
          type="date"
          value-format="timestamp"
          format="yyyy-MM-dd 00:00:00"
          clearable
          placeholder="牙模收到时间"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
        </el-date-picker>
        <el-date-picker
          v-model="query.reportUploadDate"
          type="date"
          value-format="timestamp"
          format="yyyy-MM-dd 00:00:00"
          clearable
          placeholder="报告上传时间"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        >
        </el-date-picker>
        <el-select v-model="query.patientStat" placeholder="患者状态" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in dict.patient_stat" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="query.reportResult" placeholder="报告诊断结果" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in dict.report_result" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="query.reportStat" placeholder="报告状态" clearable style="width: 200px" class="filter-item">
          <el-option v-for="item in dict.report_stat" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <crudOperation>
          <el-button
            slot="left"
            :loading="crud.downloadLoading"
            :disabled="!crud.data.length"
            size="mini"
            type="warning"
            icon="el-icon-download"
            @click="doExport"
          >导出</el-button>
          <rrOperation slot="optsLeft" :crud="crud"></rrOperation>
        </crudOperation>
      </div>
      <patient-edit></patient-edit>
      <el-dialog
        class="dialog-patient"
        :append-to-body="true"
        :title="current.label"
        :visible.sync="visibleDialog"
        :width="current.value === 'rule' ? '600px' : '800px'"
        @close="visibleDialog = false"
      >
        <patient-rule v-if="current.value === 'rule'" @closeDialog="dialogSubmit"></patient-rule>
        <patient-transfer v-if="current.value === 'transfer'" @closeDialog="dialogSubmit"></patient-transfer>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        stripe
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="areaName" sortable label="所属区域" width="120"></el-table-column>
        <el-table-column prop="salesName" sortable label="所属销售" width="120"></el-table-column>
        <el-table-column prop="proName" sortable label="诊所省份" width="120"></el-table-column>
        <el-table-column prop="cityName" sortable label="诊所城市" width="120"></el-table-column>
        <el-table-column prop="clinicName" sortable label="诊所名称" width="120"></el-table-column>
        <el-table-column prop="groupName" sortable label="所属集团" width="120"></el-table-column>
        <el-table-column prop="clinicType" sortable label="诊所性质" width="120">
          <template slot-scope="scope">
            {{ dict.label.clinic_type[scope.row.clinicType] }}
          </template>
        </el-table-column>
        <el-table-column prop="patientName" sortable label="患者姓名" width="120"></el-table-column>
        <el-table-column prop="id" sortable label="患者编号" width="120"></el-table-column>
        <el-table-column prop="createDate" sortable label="创建时间" width="140">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" sortable label="患者性别" width="120">
          <template slot-scope="scope">
            {{ dict.label.gender[scope.row.gender] }}
          </template>
        </el-table-column>
        <el-table-column prop="tags" sortable label="患者标签" width="120">
          <template slot-scope="scope">
            <span v-for="(item, index) in scope.row.tags ? scope.row.tags.tags : []" :key="index">{{ item.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="doctorName" sortable label="主治医生" width="120"></el-table-column>
        <el-table-column prop="submitDate" sortable label="提交资料时间" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.submitDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stlFlag" sortable label="牙模类型" width="120">
          <template slot-scope="scope">
            {{ dict.label.stl_flag[scope.row.stlFlag] }}
          </template>
        </el-table-column>
        <el-table-column prop="dentalCastRecvDate" sortable label="牙模收到时间" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.dentalCastRecvDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportStat" sortable label="报告状态" width="120">
          <template slot-scope="scope">
            <span>{{ dict.label.report_stat[scope.row.reportStat] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportUploadDate" sortable label="报告上传时间" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.reportUploadDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportResult" sortable label="诊断结果" width="120">
          <template slot-scope="scope">
            {{ dict.label.report_result[scope.row.reportResult] }}
          </template>
        </el-table-column>
        <el-table-column prop="makeDate" sortable label="医生确认制作时间" width="190">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.makeDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="packageName" sortable label="套餐名称" width="120"></el-table-column>
        <el-table-column prop="packageStat" sortable label="套餐状态" width="120">
          <!-- <template slot-scope="scope">
            {{ dict.label.stl_flag[scope.row.packageStat] }}
          </template> -->
        </el-table-column>
        <el-table-column prop="phase" sortable label="诊疗阶段" width="120">
          <template slot-scope="scope">
            {{ dict.label.medical_phase[scope.row.phase] }}
          </template>
        </el-table-column>
        <el-table-column prop="productName" sortable label="当前矫治器类型" width="170"></el-table-column>
        <el-table-column prop="recordStat" sortable label="诊疗状态" width="120">
          <template slot-scope="scope">
            {{ dict.label.record_stat[scope.row.recordStat] }}
          </template>
        </el-table-column>
        <el-table-column prop="patientStat" sortable label="患者状态" width="120">
          <template slot-scope="scope">
            {{ dict.label.patient_stat[scope.row.patientStat] }}
          </template>
        </el-table-column>
        <el-table-column prop="logisticsStat" sortable label="物流状态" width="120"></el-table-column>
        <el-table-column prop="packageRule" sortable label="套餐规则" width="120"></el-table-column>
        <el-table-column prop="productRule" sortable label="产品规则" width="120"></el-table-column>
        <el-table-column
          v-permission="['admin', 'oper:patient:edit']"
          label="操作"
          width="150px"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission"></udOperation>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination></pagination>
    </div>
  </div>
</template>

<script>
import { saleArea } from '@/api/order';
import { download } from '@/api/data';
import { downloadFile } from '@/utils/index';
import crudPatient from '@/api/patient';
import {
  queryPatientPut,
  queryOper,
  queryPatient,
  queryOrg,
  queryDoctor
} from '@/api/operPatient';
import CRUD, { presenter, header, crud } from '@crud/crud';
import rrOperation from '@crud/RR.operation';
import crudOperation from '@crud/CRUD.operation';
import udOperation from '@crud/UD.operation';
import pagination from '@crud/Pagination';
import patientEdit from '@/views/oper/patient/patient-edit'; // 编辑
import patientTransfer from '@/views/oper/patient/patient-transfer'; // 患者转移
import patientRule from '@/views/oper/patient/patient-rule';
import { mapMutations, mapGetters } from 'vuex';

export default {
  name: 'Patient',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    patientEdit,
    patientTransfer,
    patientRule
  },
  mixins: [presenter(), header(), crud()],
  dicts: [
    'gender', // 性别
    'patient_parent_rel',
    'stl_flag', // 牙模类型
    'record_stat', // 诊疗状态
    'medical_phase', // 诊疗阶段
    'clinic_type', // 诊所性质
    'patient_stat', // 患者状态
    'report_result', // 报告诊断结果
    'report_stat' // 报告状态
  ],
  cruds() {
    return CRUD({
      title: '患者',
      url: '/patient/queryPage',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudPatient },
      props: { searchToggle: true },
      query: {
        archived: 0
      },
      optShow: {
        add: false,
        edit: false,
        del: true,
        download: false,
        reset: true
      },
      optRightShow: {
        search: false,
        refresh: false
      }
    });
  },
  data() {
    return {
      current: {},
      visibleDialog: false,
      loading: false,
      province: [], // 省
      city: [],
      packageNameList: [], // 套餐类型
      productNameList: [], // 矫治器类型
      // 模糊匹配初始化数据
      patientList: [], // 患者名字
      clinicList: [], // 诊所名称
      groupList: [], // 所属集团
      doctorList: [], // 主治医生
      // 模糊匹配动态数据
      patientNameList: [], // 患者名字
      clinicNameList: [], // 诊所名称
      groupNameList: [], // 所属集团
      doctorNameList: [], // 主治医生
      permission: {
        add: ['admin', 'patient:add'],
        edit: ['admin', 'oper:patient:edit'],
        del: ['admin', 'oper:patient:del']
      }
    };
  },
  computed: {
    ...mapGetters(['linkSearch'])
  },
  watch: {
    'query.proCode': function(newValue, oldValue) {
      this.query.cityCode = null;
    }
  },
  mounted() {
    // 获取下拉框数据
    this.$nextTick(() => {
      this.initList();
    });
    console.log('患者管理linkSearch------', this.linkSearch);
  },
  methods: {
    ...mapMutations({
      'CHANGE_LINKSEARCH': 'settings/CHANGE_LINKSEARCH'
    }),
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    },
    initList() {
      // 患者名称
      queryPatient('queryPatientName', { patientName: '' })
        .then((res) => {
          this.patientList = res.map((item) => {
            item.label = item.patientName;
            return item;
          });
        })
        .catch((er) => {});
      // 诊所名称
      queryOrg('clinic/configList', { clinicName: '' })
        .then((res) => {
          this.clinicList = res.map((item) => {
            item.label = item.clinicName;
            return item;
          });
        })
        .catch((er) => {});
      // 所属集团
      queryOrg('group/configList', { groupName: '' })
        .then((res) => {
          this.groupList = res.map((item) => {
            item.label = item.groupName;
            return item;
          });
        })
        .catch((er) => {});
      // 主治医生
      queryDoctor('configList', { doctorName: '' })
        .then((res) => {
          this.doctorList = res.map((item) => {
            item.label = item.doctorName;
            return item;
          });
        })
        .catch((er) => {});
      // 省
      saleArea({ parentAreaId: '-1', sonlevel: '1' })
        .then((res) => {
          this.province = res;
        })
        .catch((er) => {});
      // 套餐类型
      queryOper('package/configList', { packageName: '' })
        .then((res) => {
          this.packageNameList = res;
        })
        .catch((er) => {});
      // 矫治器类型
      queryOper('product/configList', { productName: '' })
        .then((res) => {
          this.productNameList = res;
        })
        .catch((er) => {});
    },
    // 模糊查询
    remoteMethod(query, list) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this[`${list}NameList`] = this[`${list}List`].filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this[`${list}NameList`] = [];
      }
    },
    // 患者姓名
    queryPatientName(query) {
      this.remoteMethod(query, 'patient');
    },
    // 诊所名称
    queryClinicName(query) {
      this.remoteMethod(query, 'clinic');
    },
    // 所属集团
    queryGroupName(query) {
      this.remoteMethod(query, 'group');
    },
    // 主治医生
    queryDoctorName(query) {
      this.remoteMethod(query, 'doctor');
    },
    // 省切换
    provinceChange(parentAreaId) {
      // this.$forceUpdate();
      // this.city = [];
      saleArea({ parentAreaId, sonlevel: '2' })
        .then((res) => {
          this.city = res;
        })
        .catch((er) => {
          this.city = [];
        });
    },
    // 弹窗
    disDialog(item) {
      this.current = item;
      this.visibleDialog = true;
    },
    // 提交成功
    dialogSubmit(v) {
      this.visibleDialog = false;
      v ? this.crud.refresh() : '';
    },
    // 导出
    doExport() {
      this.crud.downloadLoading = true;
      download('/patient/download', this.crud.getQueryParams(), 'VUE_APP_PRIVATE_API')
        .then((result) => {
          downloadFile(result, this.crud.title + '数据', 'xlsx');
          this.crud.downloadLoading = false;
        })
        .catch(() => {
          this.crud.downloadLoading = false;
        });
    },
    // 删除
    toDelete() {
      this.$confirm(`删除后此患者全部相关病例订单将全部删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const ids = this.crud.selections.map((item) => {
            return item.id;
          });
          queryPatientPut('archive', { archived: 2, patientIds: ids })
            .then((res) => {
              this.crud.delSuccessNotify();// 删除提示
              this.crud.refresh();// 刷新列表数据
            }).catch((er) => {});
        })
        .catch(() => {});
    }
  },
  destroyed() {
    this.CHANGE_LINKSEARCH('');
  }
};
</script>

<style lang='scss'>
.dialog-patient {
  .dialog-footer {
    overflow: hidden;
    margin-top: 20px;
  }
  .dialog-footer button {
    float: right;
    margin-left: 20px;
  }
}
</style>
<style scoped>
.topOperation > .el-button {
  margin-right: 10px;
  margin-bottom: 20px;
}
.filter-item {
  margin-bottom: 5px;
}
</style>
